// import * as schedule from "node-schedule";
import * as fs from "fs";
// import { getStat } from "../utils/fs";
import path from "path";
import { fileURLToPath } from "url";
// import { success, fail } from "../utils/base";
import type { Stats } from "fs";

/**
 * @description: 这里查询日志
 * 1. 分页查询
 * 2. 根据用户 sid/邮箱 实时查询
 * 3. 根据-时间戳-查询
 */
export default defineEventHandler(async (event) => {
  // 获取请求参数 post
  const body = await readBody(event);
  // 获取当前文件的 Path
  const { filePath, filePathRoot } = getCurrentDirPath(
    "/public/log",
    "watch-log.json"
  );
  const saveFilePath = filePathRoot || filePath;

  // 获取文件大小
  if (body.getsize == 1) {
    let fileSize = 0;
    const stat: Stats = (await getStat(saveFilePath!)) as Stats;
    if (stat.size > 0) {
      fileSize = stat.size / 1024 / 1024 + 1;
    }
    return success(`文件:${fileSize}M`);
  }
  // 操作数据
  let isHas;
  try {
    const stat: Stats = (await getStat(saveFilePath)) as Stats;
    isHas = !!stat;
  } catch (error) {
    return fail("路径不存在,暂无数据");
  }

  if (isHas) {
    // 校验参数的正确性
    if (!body.pageNumber || !body.pageSize) {
      return fail(`pageNumber,pageSize参数错误`);
    }
    // 读取文件数据
    const read = () => {
      return new Promise((resolve, reject) => {
        fs.readFile(saveFilePath, "utf8", (error, jsonString) => {
          if (error) {
            console.log("❌读取失败", error);
            return reject(false);
          }
          const fileData = JSON.parse(jsonString);
          fileData.total = fileData.list.length;
          // 时间倒序
          if (fileData.list.length > 2) {
            fileData.list = fileData.list.sort((a: any, b: any) => {
              return b.data.time - a.data.time;
            });
          }
          // 错误统计
          let errorTypes: string[] = [];
          let errorTypeObjs: any = [];
          fileData.list.forEach((element: any) => {
            // 1. 不同的错误
            if (!errorTypes.includes(element.data.errorId)) {
              errorTypes.push(element.data.errorId);
              errorTypeObjs.push({
                id: element.data.errorId,
                info: element.data,
                nums: 1,
              });
            }
            // 2. 相同数量➕1
            else {
              errorTypeObjs.forEach((e: any) => {
                if (e.info.errorId == element.data.errorId) {
                  e.nums += 1;
                }
              });
            }
          });
          // 根据错误 errorType 过滤
          if (body.errorType) {
            fileData.list = fileData.list.filter((e: any) => {
              return e.data.type === body.errorType;
            });
            fileData.total = fileData.list.length;
          }
          // 根基userSid 过滤
          if (body.userSid) {
            fileData.list = fileData.list.filter((e: any) => {
              return e.authInfo.trackerId === body.userSid;
            });
            fileData.total = fileData.list.length;
          }

          // 根据 errorId 过滤
          if (body.errorId) {
            fileData.list = fileData.list.filter((e: any) => {
              return e.data.errorId == body.errorId;
            });
            fileData.total = fileData.list.length;
          }

          // 根基 data.message 过滤
          if (body.message) {
            fileData.list = fileData.list.filter((e: any) => {
              if (e.data.message) {
                return e.data.message.includes(body.message);
              } else {
                return false;
              }
            });
            fileData.total = fileData.list.length;
          }

          // 根据时间过滤
          if (!body.beginTime && body.endTime) {
            return reject("请传入beginTime字段");
          } else if (body.beginTime && !body.endTime) {
            return reject("请传入endTime字段");
          } else if (body.beginTime && body.endTime) {
            fileData.list = fileData.list.filter((e: any) => {
              const begin = new Date(e.time).getTime();
              if (begin >= body.beginTime && begin <= body.endTime) {
                return true;
              }
              return false;
            });
            fileData.total = fileData.list.length;
          }

          // 根据分页返回数据
          if (fileData.list && fileData.list.length > 0) {
            if (fileData.list.length > (body.pageNumber - 1) * body.pageSize) {
              const results = fileData.list.slice(
                (body.pageNumber - 1) * body.pageSize,
                body.pageNumber * body.pageSize
              );
              resolve({
                create: fileData.create,
                total: fileData.total,
                list: results,
                statistics: errorTypeObjs,
              });
            } else {
              resolve({
                create: fileData.create,
                list: [],
                total: fileData.total,
                statistics: errorTypeObjs,
              });
            }
          } else {
            resolve({
              create: fileData.create,
              list: [],
              total: fileData.total,
              statistics: [],
            });
          }
          // resolve(fileData);
        });
      });
    };
    try {
      const json = await read();
      return success(json);
    } catch (error) {
      return fail(error);
    }
  } else {
    return fail("文件未创建,暂无数据");
  }
});
